//
//  UITextView+emoticon.swift
//  表情键盘
//
//  Created by 雄 on 15/7/21.
//  Copyright © 2015年 雄. All rights reserved.
//

import UIKit

extension UITextView {
    
    // 插入表情
    func insertEmoticon(emoticon: Emoticon) {
        
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji ?? "")
        }
        
        if emoticon.chs != nil {
            
            // 1. 生成表情文本,字体已设置
            let imageTextM = EmoticonAttachment.emoticonStr(emoticon, font: font!)
            
            // 2. 设置textView attributeText 为可变
            let textM = NSMutableAttributedString(attributedString: attributedText)
            
            // 3. 插入表情文本
            textM.replaceCharactersInRange(selectedRange, withAttributedString: imageTextM)
            
            // 4. 记录光标位置
            let range = selectedRange
            
            // 5. 改变后的文本设给textView
            attributedText = textM
            
            // 6. 光标设在插入内容之后
            selectedRange = NSRange(location: range.location + 1, length: 0)
        }
    }

    // 输出文本和表情文本
     func emoticonText() -> String{
        
        var strM = String()
        
        // 遍历
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions.LongestEffectiveRangeNotRequired) { (dict, range, _) -> Void in
            
            // dict["NSattachment"] 有值表示有 表情图片
            let attachment = dict["NSAttachment"] as? EmoticonAttachment
            if  attachment != nil {
                strM += attachment!.chs ?? ""
            } else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        
        return strM
    }

}


